package com.yicong.ants.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.yicong.ants.Constants;

public class X5WebViewBackup extends WebView {

    private WebSettings webSetting;

    public X5WebViewBackup(Context arg0) {
        super(arg0);
        init();
    }

    @SuppressLint("SetJavaScriptEnabled")
    public X5WebViewBackup(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
        init();
    }

    public X5WebViewBackup(Context var1, AttributeSet var2, int var3) {
        super(var1, var2, var3, false);
        init();
    }

    private WebViewClient initWebViewClient() {
        return new WebViewClient() {
            /**
             * 防止加载网页时调起系统浏览器
             */
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (TextUtils.isEmpty(url)) {
                    return false;
                }
                try {
                    if (url.startsWith("weixin://") || url.startsWith("alipays://")
                        || url.startsWith("tel:")) {
                        if (null != view.getContext() && view.getContext() instanceof Activity) {
                            Activity activity = (Activity) view.getContext();
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                            activity.startActivity(intent);
                            return true;
                        }
                    }
                } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return false;
                }
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                view.loadUrl(Constants.ERROR_HTML);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
                //view.loadUrl(Constants.ERROR_HTML);
                handler.proceed();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                view.loadUrl(Constants.ERROR_HTML);
            }
        };
    }

    private void init() {
        setWebChromeClient(new WebChromeClient() {
        });
        this.setWebViewClient(initWebViewClient());
        webSetting = this.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setTextSize(WebSettings.TextSize.NORMAL);
        //webSetting.setSupportZoom(true);
        //  webSetting.setBuiltInZoomControls(true);
        // webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        webSetting.setLoadWithOverviewMode(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        // webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension
        // settings 的设计
        // 19  4.4  Build.VERSION.KITKAT
        // 11  3.0  Build.VERSION_CODES.HONEYCOMB
        /**
         android webview 组件包含3个隐藏的系统接口：
         searchBoxJavaBridge_  accessibilityTraversal 以及 accessibility
         恶意程序可以通过反射机制利用它们实现远程代码执行
         在Android3.0到4.4之间的版本，通过移除这些隐藏接口解决该问题
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB
            && Build.VERSION.SDK_INT < 19) {
            removeJavascriptInterface("searchBoxJavaBridge_");
            removeJavascriptInterface("accessibility");
            removeJavascriptInterface("accessibilityTraversal");
        }
    }

    public void setHtmlTextSize(int textZoom, int fontSize) {
        webSetting.setTextSize(WebSettings.TextSize.LARGER);
        webSetting.setTextZoom(textZoom);
        webSetting.setDefaultFontSize(fontSize);
    }

    /**
     * 清理 webview
     */
    public void clearWebview() {
        this.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
        this.clearHistory();
        ((ViewGroup) this.getParent()).removeView(this);
        this.destroy();
    }


}
